import 'dart:io';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';

export 'videoFormat.dart'; // 导出 Body 类
class VideoFormat extends StatefulWidget {
  const VideoFormat({Key? key}) : super(key: key);

  @override
  _BodyState createState() => _BodyState();
}

class _BodyState extends State<VideoFormat> {
  List<Map> selectedFileNames = [];
  var outputPath = "D:\\";
  SharedPreferences? _prefs;
  _BodyState() {
    // for (var i = 0; i < 20; i++) {
    //   selectedFileNames.add("file$i.jpg");
    // }
    _initPrefs();
  }
  @override
  void onWindowFocus() {
    // Make sure to call once.
    setState(() {});
    // do something
  }

  Future<void> _initPrefs() async {
    // 读取之前存储的outputPath
    String? storedPath = _prefs?.getString('output_path');
    if (storedPath != null) {
      // 如果之前有存储的path，则设置到outputPath
      setState(() {
        outputPath = storedPath;
      });
    }
    // print(storedPath);
  }

  void _setDirPath(String path) async {
    setState(() {
      outputPath = path;
      //永久存储，下次启动读出来
    });
    // 永久存储到SharedPreferences
    final SharedPreferences _prefs = await SharedPreferences.getInstance();
    await _prefs.setString('output_path', path);
  }

  // 添加list列表
  void _addFileName(String fileName) {
    setState(() {
      //查看是否已经有重复了
      var flag = false;
      for (var i = 0; i < selectedFileNames.length; i++) {
        if (selectedFileNames[i]["fileName"] == fileName) {
          flag = true;
          break;
        }
      }
      if (!flag) {
        selectedFileNames.add({"fileName": fileName, "status": 0, "msg": ""});
      }
    });
  }

  //设置列表
  void _setFileList(List<Map> data) {
    setState(() {
      selectedFileNames = data;
    });
  }

  //获取list列表
  _getFileNames() async {
    return selectedFileNames;
  }

  // 解析错误信息的函数
  String _parseErrorMessage(String line) {
    int index = line.lastIndexOf(":");
    if (index != -1 && index < line.length - 1) {
      return line.substring(index + 1).trim();
    } else {
      return "未知错误"; // 如果无法解析错误信息，返回默认错误信息
    }
  }

  _RunFFMPEG(String fileName) async {
    File originalFile = File(fileName);
    //获取文件名
    // String fileNameWithoutExtension =
    //     originalFile.path.split('\\').last.split('.').first;
    //获取文件扩展名
    // String fileExtension = originalFile.path.split('\\').last.split('.').last;
    // 通过正则表达式匹配文件名中最后一个`.`之前的内容//获取文件名
    RegExp regex = RegExp(r'(.*)\.[^.]+$');
    String fileNameWithoutExtension = regex
        .firstMatch(originalFile.path.split(Platform.pathSeparator).last)!
        .group(1)!;
    //拼接新的文件路径
    String newFilePath = '$outputPath\\$fileNameWithoutExtension.mp4';

    // ffmpeg -i input.ext -vcodec copy -acodec copy output.mp4
    // ffmpeg -i input.ext -vcodec libx264 -acodec aac -strict -2 output.mp4
    //获取当前程序路径
    String ffmpegPath =
        "${Directory.current.path}\\ffmpeg-4.3.1-2020-11-19-essentials_build\\bin\\ffmpeg.exe";
    //先查看是否有ffmpegPath文件
    if (!File(ffmpegPath).existsSync()) {
      //如果没有，则提示用户下载
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
                title: const Text('提示'),
                content: Text(
                    "请先下载ffmpeg-4.3.1-2020-11-19-essentials_build，并放置在:${Directory.current.path}\\ffmpeg-4.3.1-2020-11-19-essentials_build"),
                actions: <Widget>[
                  TextButton(
                    child: const Text('确定'),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  )
                ]);
          });
    } else {
      //拼接ffmpeg命令
      String cmds =
          "$ffmpegPath -y -i $fileName -vcodec libx264 -acodec aac -strict -2 $newFilePath";
      print('执行命令：$cmds');
      ProcessResult result = await Process.run('cmd', ['/c', cmds]);
      var code = result.exitCode;
      // 打印执行结果
      print('stdout: ${result.stdout}');
      print('stderr: ${result.stderr}');
      // 根据exitCode判断命令是否成功执行
      if (code == 0) {
        // print('FFmpeg命令执行成功');
        for (var i = 0; i < selectedFileNames.length; i++) {
          if (selectedFileNames[i]["fileName"] == fileName) {
            setState(() {
              selectedFileNames[i]["status"] = 1;
            });
          }
        }
      } else {
        // print('FFmpeg命令执行失败，错误码：${code}');
        for (var i = 0; i < selectedFileNames.length; i++) {
          if (selectedFileNames[i]["fileName"] == fileName) {
            setState(() {
              selectedFileNames[i]["status"] = 2;
              selectedFileNames[i]["msg"] =
                  _parseErrorMessage(result.stderr.toString());
            });
          }
        }
      }
    }
    // 转换视频格式 mp4、avi、mov、flv、wmv、mkv、webm、mpeg、mpg、m4v、m4a、3gp、3g2、ts、vob、asf、wmv、flv、f4v、f4p、f4a、f4b、f4s、f4v
  }

  String getStatusText(Map fileInfo) {
    int status = fileInfo["status"];
    if (status == 0) {
      return '转换中';
    } else if (status == 1) {
      return '已完成';
    } else if (status == 2) {
      return fileInfo.containsKey("msg") ? fileInfo["msg"] : '失败';
    } else {
      return '未知状态';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(children: [
      // const Positioned(
      //     right: 10,
      //     bottom: 20,
      //     child: Icon(
      //       Icons.settings,
      //       size: 40,
      //       color: Colors.blue,
      //     )),
      Center(
        child: Column(
          children: [
            const SizedBox(height: 40),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                AddFile(
                    onFileSelected: _addFileName,
                    getFiles: _getFileNames,
                    setFileList: _setFileList,
                    runFFMPEG: _RunFFMPEG),
                const SizedBox(width: 10),
                SetPath(
                  setDirPath: _setDirPath,
                ),
                const SizedBox(width: 10),
                ElevatedButton(
                  onPressed: () {
                    var flag = false;
                    for (var item in selectedFileNames) {
                      if (item["status"] == 0) {
                        flag = true;
                      }
                    }
                    if (flag) {
                      //先提示是否重置
                      showDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return AlertDialog(
                                title: const Text('提示'),
                                content: const Text('当前有任务正在进行中，是否重置？'),
                                actions: <Widget>[
                                  TextButton(
                                    child: const Text('取消'),
                                    onPressed: () {
                                      Navigator.of(context).pop();
                                    },
                                  ),
                                  TextButton(
                                      child: const Text('确定'),
                                      onPressed: () {
                                        setState(() {
                                          selectedFileNames = [];
                                        });
                                        Navigator.of(context).pop();
                                      })
                                ]);
                          });
                    } else {
                      setState(() {
                        selectedFileNames = [];
                      });
                    }
                  },
                  child: const Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text('重置'),
                    ],
                  ),
                )
              ],
            ),
            Text("输出路径：$outputPath"),
            const SizedBox(height: 10),
            Container(
              width: 800,
              height: 500,
              decoration: BoxDecoration(
                color:
                    const Color.fromARGB(255,247, 242, 249), //Container的背景颜色
                borderRadius:
                    const BorderRadius.all(Radius.circular(8)), //Container的圆角
                border: Border.all(
                    color: Color.fromARGB(255, 103, 80, 164), width: 1),
                boxShadow: [
                  //Container的阴影
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.5),
                    spreadRadius: 5,
                    blurRadius: 7,
                    offset: const Offset(0, 3),
                  )
                ],
              ),
              child: ListView.builder(
                itemCount: selectedFileNames.length,
                itemBuilder: (context, index) {
                  return Column(
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Flex(direction: Axis.horizontal, children: [
                            Expanded(
                                flex: 11,
                                child: ListTile(
                                  leading: const Icon(Icons.abc),
                                  title: Text(
                                      "${index + 1} ${selectedFileNames[index]["fileName"]}"),
                                )),
                            Expanded(
                              flex: 1,
                              child:
                                  Text(getStatusText(selectedFileNames[index])),
                            ),
                          ]),
                        ],
                      ),
                      const Divider(
                        color: Colors.black,
                      ), //下划线
                    ],
                  );
                },
              ),
            ),
          ],
        ),
      ),
    ]);
  }
}

//添加文件
class AddFile extends StatelessWidget {
  final Function(String) onFileSelected;
  final Function() getFiles;
  final Function(List<Map>) setFileList;
  final Function(String) runFFMPEG;

  AddFile(
      {super.key,
      required this.onFileSelected,
      required this.getFiles,
      required this.setFileList,
      required this.runFFMPEG});

  Future<void> _openFile(BuildContext context) async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      allowMultiple: true,
      type: FileType.custom,
      allowedExtensions: ['mov', 'avi', 'mkv', 'mp4', 'flv', 'wmv', '3gp'],
    );

    if (result != null) {
      List<String> fileNames = result.paths.map((path) => path!).toList();
      for (String fileName in fileNames) {
        onFileSelected(fileName);
      }
      var data = await getFiles();
      for (var item in data) {
        if (item["status"] == 0) {
          //等待2s
          // await Future.delayed(const Duration(seconds: 2));
          await runFFMPEG(item["fileName"]);
          // item["status"] = true;
          // setFileList(data); 
        }
      }

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: const Text('转换完成'),
          action: SnackBarAction(
            label: '确定',
            onPressed: () {
              // 按钮点击后的操作
            },
          ),
        ),
      );

      // 将选定的文件拷贝到桌面
    } else {
      // User canceled the picker
    }
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        _openFile(context);
      },
      child: const Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.add),
          SizedBox(width: 8),
          Text('选择文件'),
        ],
      ),
    );
  }
}

//设置路径
class SetPath extends StatelessWidget {
  final Function(String) setDirPath;

  const SetPath({super.key, required this.setDirPath});
  Future<void> _selectDir(BuildContext context) async {
    String? selectedDirectory = await FilePicker.platform.getDirectoryPath();

    if (selectedDirectory != null) {
      setDirPath(selectedDirectory);
    }
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        _selectDir(context);
      },
      child: const Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.settings),
          SizedBox(width: 8),
          Text('设置输出路径'),
        ],
      ),
    );
  }
}